//
//  OAuthViewController.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/4.
//  Copyright © 2015年 002. All rights reserved.
//

#import "OAuthViewController.h"
#import "NetworkTools.h"
#import "SVProgressHUD.h"
#import "UserAccount.h"
#import "UserAccountViewModel.h"

@interface OAuthViewController ()<UIWebViewDelegate>

@property(nonatomic,strong) UIWebView *webView;
@property(nonatomic,strong) UserAccount *userAccount;


@end

@implementation OAuthViewController


#pragma mark - 监听方法
/**
 *  关闭当前控制器
 */
- (void)close {
    
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:true completion:nil];
}

#pragma mark - 视图生命周期
- (void)loadView {
    self.view = self.webView;
    
    self.title = @"登录新浪微博";
    
    // 设置导航栏
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
    
    // 设置代理
    self.webView.delegate = self;
    // 加载授权页面
    [self.webView loadRequest:[[NSURLRequest alloc]initWithURL:[NetworkTools sharedTools].oauthUrl]];

}

/**
 * 自动填充用户名和密码 － web 注入（以代码的方式向web页面添加内容）
 */
- (void)autoFill {
    
    NSString *js = [NSString stringWithFormat:@"document.getElementById('userId').value = '%@';document.getElementById('passwd').value = '%@';",@"13163068587",@"247689520"];
    
    // 让 webView 执行 js
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

#pragma mark - UIWebViewDelegate
/**
 *  是否加载请求
 *
 *  @param webView        webView
 *  @param request        要加载的请求
 *  @param navigationType 导航类型
 *
 *  @return 是否加载当前请求  返回 false 不加载（不再调用此方法），返回 true 继续加载（结束此次调用并重新继续调用此方法）
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSLog(@"request==%@",request);
    
    // 1. 判断请求地址是否是百度，不是则继续加载
    if (![request.URL.host isEqualToString:@"www.baidu.com"]) {
        
        NSLog(@"继续加载%@",request);
        return true;
    }
    
    // 2. 判断请求地址的查询参数是否包含 code
    if (![request.URL.query containsString:@"code="]) {
        NSLog(@"取消");
        [self close];
        return true;
    }
    
    // 3. 从查询字符串中取出授权码
    NSString *code = [request.URL.query substringFromIndex:@"code=".length];
    NSLog(@"授权码：%@",code);
    
    // 4. 根据 code 加载 Token & 用户信息
    [[UserAccountViewModel sharedAccountViewModel] loadAccessTokenWithCode:code finished:^(BOOL isSuccessed) {
       
        if (!isSuccessed) {
            [SVProgressHUD showInfoWithStatus:@"登录失败"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self close];
            });
        } else {
            // 登录成功后发送通知 - 进入主界面
            [SVProgressHUD dismiss];             
            [self dismissViewControllerAnimated:false completion:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:WBSwitchRootViewControllerNotification object:@"welcome"];
            }];
        }
    }];
    return true;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [SVProgressHUD show];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [SVProgressHUD dismiss];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {

    // 102 用户是否中断
    if (error.code == 102) {
        [SVProgressHUD dismiss];
    } else {
        [SVProgressHUD showInfoWithStatus:@"您的网络不给力"];
    }
}

#pragma mark - 懒加载控件
- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _webView;
}

@end
